import myConfig from '@/config.js'
import store from '@/store/index.js'
import * as util from '@/common/js/util'
//异步请求
export default function baseRequest(url, params = {}, method = 'GET', contentType = 'application/x-www-form-urlencoded') {
	let header = {
		'Authorization': uni.getStorageSync('token'),
		'content-type': 'application/json;charset=UTF-8'
	}
	if (method == 'POST') header['content-type'] = contentType
	const httpDefaultOpts = {
		url: (url.indexOf('http') > -1? '':`${myConfig.base_url}`) + `${url}`,
		data: params,
		method: method,
		header: header
	}
	return new Promise((resolve, reject) => {
		uni.request(httpDefaultOpts).then(response => {
			if (response[0]) {
				util.showToast(response[0])
				reject(response)
			}
			const data = response[1].data
			data.success = true
			if (data.code !== "00000" && parseInt(data.code) != 200) {
				handleError(data)
				data.success = false
			}
			resolve(data)
		}).catch(response => {
			console.error(response)
			util.showToast(response) //'未知错误'
		})
	})
}

function handleError(data) {
	let {
		code,
		error,
		message
	} = data
	let loginComfirmModal = uni.getStorageSync('loginComfirmModal')
	switch (code) {
		case 401:
			let mineUrl = 'pages/mine/index'
			const pages = getCurrentPages()
			if (!loginComfirmModal) {
				// 移除本地保存信息
				store.commit('logout')
				uni.setStorageSync('loginComfirmModal', true)
				util.showModal('用户登陆', '操作失败！当前用户未登录，是否进行登陆操作？', true, '确定', '取消', (res) => {
					uni.setStorageSync('loginComfirmModal', false)
					if (!pages || ((pages.route && pages.route != mineUrl) || (pages instanceof Array && pages[pages.length - 1].route != mineUrl))) {
						uni.reLaunch({
							url: '/' + mineUrl
						})
					}
				}, (res) => {
					uni.setStorageSync("loginComfirmModal", false)
				})
			}
			break;
		case 402:
			//getContext().$i18nMsg().login.checkParam
			// if(msg !== 'Authorization'){
			// 	util.showToast('参数错误', 'none', 1000, false)
			// }else {
			// 	if (!isExpired) {
			// 		store.commit('logout')
			// 		util.showToast('access-token is wrong', 'none', 3000, false)
			// 		uni.reLaunch({
			// 			url: '/pages/login/login'
			// 		})
			// 	}
			// }
			// uni.setStorageSync('isExpired', true)
			break;
		case 201:

			break
		default:
			util.showToast(message || error, 'none', 3000, false)
	}
}
